var express = require("express");
var router = express.Router();
const connect = require("../public/javascripts/conn.js");
var crypto = require("crypto");

// 登录页面渲染
router.get("/", function (req, res, next) {
  res.render("register&login", { title: "登录" });
});

// 解决跨域问题  用于前端请求
router.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

// 登录接口设置
router.post("/", function (req, res, next) {
  // 获取前端传递的用户名和密码
  var username = req.body.username;
  // 对密码进行加密处理采用sha256加密，生成十六进制字符串
  var password = crypto
    .createHmac("sha256", req.body.password)
    .update("secret password")
    .digest("hex");
  // 查询数据库，判断用户名和密码是否正确
  connect.query(
    `select * from user where username="${username}" and password="${password}";`,
    function (err, result) {
      // 查询出错时err才会有值
      console.log(err, result); // result 会返回sql查询到的信息，没有查询到时返回[]
      console.log(result.length); // 查询到数据时result.length>0
      if (result.length == 0) {
        res.send({
          status: 0,
          msg: "登录失败",
        });
      } else {
        res.cookie('username', username, {maxAge: 1000* 3600* 24* 7})
        res.cookie('password', password, {maxAge: 1000* 3600* 24* 7})
        res.send({
          status: 1,
          msg: "登录成功",
        });
      }
    }
  );
});

module.exports = router;
